import time
import btce
import common
from time import gmtime, strftime

good_pair = [
"btc_usd",
"btc_rur",
"btc_eur",
"ltc_btc",
"ltc_usd",
"ltc_rur",
"usd_rur",
"eur_usd"]

mk = common.MarketGraph(common.pair2graph(good_pair))
mk.calPath("btc")
allloop = mk.allpath

class NoMoney(Exception):
	def __init__(self):
		Exception.__init__(self)
	def __str__(self):
		return "NoMoney~~"

def getPrice():
	print "getting price..."
	ret = {}
	for k in good_pair:
		t1, t2 = k.split("_")
		if t1 not in ret:ret[t1] = {}
		if t2 not in ret:ret[t2] = {}
		price = btce.getDepth(t1,t2)
		#print price
		#raw_input("blabla %s %s" % (k,v))

		##s1
#		alpha = 1.0*price[u'bids'][0][1]/(price[u'bids'][0][1]+price[u'asks'][0][1])
#		p = price[u'bids'][0][0]*(1-alpha) + price[u'asks'][0][0]*(alpha)
#		ret[t1][t2] = p
#		ret[t2][t1] = 1/p
#		
#		##s2
#		p = btce.getPrice(t1, t2)
#		ret[t1][t2] = p
#		ret[t2][t1] = 1/p
		
		##s3
		ret[t1][t2] = price[u'bids'][0][0]
		ret[t2][t1] = 1/price[u'asks'][0][0]

	print "done."
	return ret

def doTrading(weight, i):
	amo = 0.1
	for j in range(len(i)-1):
		if "%s_%s" % (i[j],i[j+1]) in good_pair:
			print i[j],i[j+1],"sell",amo, "@", weight[i[j]][i[j+1]]
			result = btce.Trade("%s_%s" % (i[j],i[j+1]), "sell", weight[i[j]][i[j+1]], amo)
			print result
			if result[u'success'] != 1:
				raise NoMoney
		else:
			print i[j+1],i[j],"buy",amo*weight[i[j]][i[j+1]],"@", 1/weight[i[j]][i[j+1]]
			result = btce.Trade("%s_%s" % (i[j+1],i[j]), "buy", 1/weight[i[j]][i[j+1]], amo*weight[i[j]][i[j+1]])
			print result
			if result[u'success'] != 1:
				raise NoMoney
		amo *= weight[i[j]][i[j+1]] * 0.998
	while True:
		try:
			order = btce.OrderList()
		except KeyboardInterrupt:
			raise
		except:
			time.sleep(10)
		finally:
			time.sleep(1)
		if order is not None:
			if order[u'success']==0 and order[u'error']==u'no orders':
				print "all clear!"
				break;
		

def getMaxProfit():
	weight = getPrice()
	heat = 0
	best = -100
	who = None
	for i in allloop:
		rate = 1
		for j in range(len(i)-1):
			rate *= weight[i[j]][i[j+1]] * 0.998
		heat += 1-rate/(0.998**(len(i)-1))
		if rate > best :
			print strftime("%b %d %X", gmtime()),i,rate
			best ,who = rate,i
	try:
		if best > 1.001 and who is not None:doTrading(weight,who)
	except Exception as e:
		raise
		print e
		raise KeyboardInterrupt
	return heat

def AllClear():
	pass
	

if __name__ == "__main__":
	print btce.getInfo()
	while True:
		try:
			heat = getMaxProfit()
			print "HEAT:",heat
		except KeyboardInterrupt:
			raise
		except:
			raise
			time.sleep(10)
		finally:
			time.sleep(1.5)
